#!/bin/bash


#当前用户名
name_fun() {
	NAME=$(cat ./user.txt)
}
#主机编号
bianhao_fun() {
	HostName=$(cat ./hostname.txt)
}
#主机IP
ip_fun() {
	IP=$(ifconfig | grep -E '\<inet\>' |  awk '/192/{print $2}')
}
#统计本地所有plot文件数量
plot_fun() {
	rm -rf /home/$NAME/plot
	lsblk  | awk -F'/' '/data/{print $NF}' > /home/$NAME/data
	m=$(cat /home/$NAME/data)
	for var in $m
	do
		ls /$var/xnjsj/*.plot | awk -F'/' '{print $4}'| sort | uniq | wc -l >> /home/$NAME/plot
	done
	PlotNumber=$(cat /home/$NAME/plot  | xargs echo -n | tr ' ' '+' | xargs echo  | bc)
}
#日志内容最近修改时间
logTime_fun() {
	TIME=$(stat -c %y /home/$NAME/.chia/mainnet/log/debug.log | awk -F. '{print $1}')
	logModifiedTime=$(date -d "$TIME" +%s)
}
#日志内容最后一行
lastLog_fun(){
	lastLine=$(tail -n 1 /home/$NAME/.chia/mainnet/log/debug.log)
}
#本地总内存、可用内存
memory_fun() {
	memory_total_available=$(free -m | awk 'NR==2{print $2,$NF}' | xargs printf '%s;%s')
}
#所有磁盘可用空间
disk_fun() {
	disk=$(df -TH | awk '/\/dev\/sd/{print $1,$(NF-2)}' | xargs printf '%s: %s;')
}
#出块统计
Found1_tj_fun() {
	Found1_Shu=$(awk '/Found 1/{print}' /home/$NAME/.chia/mainnet/log/debug.log* | wc -l)
}
#最新出块日志
Found1_log_fun() {
	Found1_content=$(awk '/Found 1/{print}' /home/$NAME/.chia/mainnet/log/debug.log* | awk 'END{print}')
}
#最新日志出块时间
Found1_lt_fun() {
	Time=$(awk '/Found 1/{print}' /home/$NAME/.chia/mainnet/log/debug.log* | awk -F[.T] 'END{print $1,$2}')
	Found_Time=$(date -d "$Time" +%s)
}


#name_fun;echo $NAME;bianhao_fun;echo $HostName;ip_fun;echo $IP;plot_fun;echo $PlotNumber;logTime_fun;echo $logModifiedTime;lastLog_fun;echo $lastLine;memory_fun;echo $memory_total_available;disk_fun;echo $disk;Found1_tj_fun;echo $Found1_Shu;Found1_log_fun;echo $Found1_content;Found1_lt_fun;echo $Found_Time

cpuName=
cpuTemp=0
cpuLoad=0
isStorage=0
processNumber=

while :
do
	name_fun;bianhao_fun;ip_fun;plot_fun;logTime_fun;lastLog_fun;memory_fun;disk_fun
	curl -i -X POST http://192.168.4.253:8080/api/host -H 'Content-type: application/json' -d '{"hostname":"'"$HostName"'","ip":"'"$IP"'","cpuName":"'"$cpuName"'","cpuLoad":"'"$cpuLoad"'","cpuTemp":"'"$cpuTemp"'","memory":"'"$memory_total_available"'","disk":"'"$disk"'","processNumber":"'"$processNumber"'","plotNumber":"'"$PlotNumber"'","logModifiedTime":"'"$logModifiedTime"'","isStorage":"'"$isStorage"'","lastLine":"'"$lastLine"'"}'
	Found1_tj_fun;Found1_log_fun;Found1_lt_fun

	if [ $Found1_Shu -gt 0 ]; then
		for ((i=1; i <= $Found1_Shu; i++))
		do	
			found1_cont=$(awk '/Found 1/{print}' /home/$NAME/.chia/mainnet/log/debug.log* | sed -n "${i}p")
			found1_time=$(awk '/Found 1/{print}' /home/$NAME/.chia/mainnet/log/debug.log* | awk -F[.T] '{print $1,$2}' | sed -n "${i}p")
			found1_timestamp=$(date -d "$found1_time" +%s)
			
			curl -i -X POST http://192.168.4.253:8080/api/found -H 'Content-type: application/json' -d '{"ip":"'"$IP"'","time":"'"$found1_timestamp"'","line":"'"$found1_cont"'"}'
			sleep 1
		done
	fi
	sleep 10
done


